package com.hxut.mrs.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hxut.mrs.common.ResponseResult;
import com.hxut.mrs.domain.LoginUser;
import com.hxut.mrs.domain.User;
import com.hxut.mrs.mapper.UserMapper;
import com.hxut.mrs.service.LoginService;
import com.hxut.mrs.utils.JwtUtil;
import com.hxut.mrs.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * description: LoginServiceImpl
 * date: 2022/7/8 8:33
 * author: MR.孙
 */
@Service
public class LoginServiceImpl extends ServiceImpl<UserMapper, User> implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(User user) {
        //使用AuthenticationManage authenticate进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //认证没通过，给出相应的提示
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("用户或密码错误");
        }

        //如果认证成功通过了，使用userid生成一个jwt,jwt存入ResponseResult
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);

        //把完整的用户信息存入redis,userid作为key
        redisCache.setCacheObject("login:"+userId,loginUser);

        //响应token给前端
        HashMap<String,String> map = new HashMap<>();
        map.put("token",jwt);
        return new ResponseResult<Map>(200,"登陆成功",map);
    }

    @Override
    public ResponseResult logout() {

        //获取SecurityContextHolder中的用户Id
        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();

        //删除redis中的值
        redisCache.deleteObject("login:"+userId);
        return new ResponseResult(200,"用户注销成功");
    }
}
